package com.hmdp.service.impl;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MutexLockDemo extends JFrame {

    private JTextArea logArea;
    private JPanel threadPanel;
    private SharedResource resource;
    private Lock lock;

    public MutexLockDemo() {
        super("Java 互斥锁示例");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 500);
        setLayout(new BorderLayout());

        lock = new ReentrantLock();
        resource = new SharedResource();

        // 创建界面组件
        createUI();

        setVisible(true);
    }

    private void createUI() {
        // 日志区域
        logArea = new JTextArea();
        logArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(logArea);
        add(scrollPane, BorderLayout.CENTER);

        // 线程控制面板
        JPanel controlPanel = new JPanel(new FlowLayout());
        JButton startButton = new JButton("启动线程");
        startButton.addActionListener(e -> startThreads());
        controlPanel.add(startButton);

        JButton clearButton = new JButton("清空日志");
        clearButton.addActionListener(e -> logArea.setText(""));
        controlPanel.add(clearButton);

        add(controlPanel, BorderLayout.SOUTH);

        // 线程状态面板
        threadPanel = new JPanel(new GridLayout(1, 5, 10, 10));
        threadPanel.setBorder(BorderFactory.createTitledBorder("线程状态"));
        add(threadPanel, BorderLayout.NORTH);
    }

    private void startThreads() {
        // 创建5个线程
        for (int i = 1; i <= 5; i++) {
            Thread thread = new Thread(new Worker(i, resource, lock));
            threadPanel.add(createThreadLabel(i));
            thread.start();
        }
        revalidate();
    }

    private JLabel createThreadLabel(int id) {
        JLabel label = new JLabel("线程 " + id, SwingConstants.CENTER);
        label.setOpaque(true);
        label.setBackground(Color.LIGHT_GRAY);
        label.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
        label.setPreferredSize(new Dimension(100, 50));
        return label;
    }

    // 工作线程类
    class Worker implements Runnable {
        private int id;
        private SharedResource resource;
        private Lock lock;

        public Worker(int id, SharedResource resource, Lock lock) {
            this.id = id;
            this.resource = resource;
            this.lock = lock;
        }

        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                try {
                    // 模拟一些工作
                    Thread.sleep((long) (Math.random() * 1000));

                    // 获取锁
                    updateThreadStatus(Color.ORANGE, "等待锁");
                    lock.lock();

                    try {
                        updateThreadStatus(Color.RED, "持有锁");
                        logArea.append("线程 " + id + " 获得了锁，访问共享资源\n");

                        // 访问共享资源
                        int value = resource.access();
                        logArea.append("线程 " + id + " 读取资源值: " + value + "\n");

                        // 模拟一些工作
                        Thread.sleep(1000);

                    } finally {
                        // 释放锁
                        lock.unlock();
                        updateThreadStatus(Color.GREEN, "释放锁");
                        logArea.append("线程 " + id + " 释放了锁\n");
                    }

                    // 锁释放后的工作
                    Thread.sleep(500);
                    updateThreadStatus(Color.LIGHT_GRAY, "等待中");

                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }

        private void updateThreadStatus(Color color, String text) {
            SwingUtilities.invokeLater(() -> {
                JLabel label = (JLabel) threadPanel.getComponent(id - 1);
                label.setBackground(color);
                label.setText("线程 " + id + ": " + text);
            });
        }
    }

    // 共享资源类
    static class SharedResource {
        private int counter = 0;

        public int access() {
            // 模拟对共享资源的访问
            return ++counter;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(MutexLockDemo::new);
    }
}